package com.superzlc.miniweb.servlet;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import com.superzlc.miniweb.servlet.anno.Controller;
import com.superzlc.miniweb.servlet.anno.RequestMapping;

public class RequestController {
	Class<?> clazz;
	String path;
	List<RequestAction> requestActionList = new ArrayList<RequestAction>();

	public String toString() {
		return clazz.getName() + " - " + path;
	}

	public RequestController(Class<?> clazz) {
		this.clazz = clazz;
	}

	public boolean init() {
		if (!clazz.isAnnotationPresent(Controller.class))
			return false;
		RequestMapping mapping = clazz.getAnnotation(RequestMapping.class);
		path = mapping != null ? mapping.value() : "";

		Method[] methods = clazz.getMethods();
		for (Method method : methods) {
			if (!method.isAnnotationPresent(RequestMapping.class))
				continue;
			System.out.println("[info] 注册Action - " + clazz.getName() + ":" + method.getName());
			RequestAction ra = new RequestAction(this, method);
			if (ra.init()) {
				System.out.println("[info] 注册Action成功，匹配" + ra.path);
				requestActionList.add(ra);
			}
		}
		if (requestActionList.size() == 0)
			return false;
		return true;
	}

	public RequestAction getRequestAction(String actionPath) {
		for (RequestAction ra : requestActionList) {
			if (ra.matchPath(actionPath))
				return ra;
		}
		return null;
	}
}
